using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;

public class EmailSender
{
    private string mailFromAddress = ConfigurationManager.AppSettings["MailFromAddress"];
    private bool useSsl = bool.Parse(ConfigurationManager.AppSettings["UseSsl"]);
    private string userName = ConfigurationManager.AppSettings["UserName"];
    private string password = ConfigurationManager.AppSettings["Password"];
    private string serverName = ConfigurationManager.AppSettings["ServerName"];
    private int serverPort = int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
    private string resetCode;  // 生成的随机数字
    private string mailToAddress = "";  // 收件人邮箱

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="address">收件人邮箱</param>
    public EmailSender(string address, string pwd)
    {
        mailToAddress = address;
        resetCode = pwd; // 新的传入密码
    }


    // 生成 4 位随机数字
    private string GenerateRandomCode()
    {
        Random random = new Random();
        return random.Next(1000, 10000).ToString(); // 生成 1000 到 9999 之间的随机数
    }

    /// <summary>
    /// 自定义方法，根据设置的SMTP服务器名、端口号、账户名、授权码等信息发送邮件
    /// </summary>
    public void Send()
    {
        using (var smtpClient = new SmtpClient())
        {
            smtpClient.EnableSsl = useSsl;
            smtpClient.Host = serverName;
            smtpClient.Port = serverPort;
            smtpClient.Credentials = new NetworkCredential(userName, password);

            string body = $"您登录MyPetShop的密码重置代码为：{resetCode}"; // 使用随机数字替换原来的密码内容
            MailMessage mailMessage = new MailMessage(
                mailFromAddress,   // 发件人邮箱
                mailToAddress,     // 收件人邮箱
                "MyPetShop用户密码重置",  // 电子邮件主题
                body);  // 电子邮件内容

            smtpClient.Send(mailMessage);
        }
    }
}